<template>
    <el-dialog title="客户发送短信" :visible.sync="showMessageDialog" @close="closeMsgDialog" class="dialog dialog-message">
        <div class="message-left">
            <el-form :model="form">
                <el-form-item label="接收人 : " :label-width="formLabelWidth">
                    <el-input
                            type="textarea"
                            autosize
                            :disabled="true"
                            placeholder="请输入客户"
                            v-model="customerInfo"
                            :autosize="{ minRows: 3}">
                    </el-input>
                </el-form-item>

                <el-form-item label="短信内容 : " :label-width="formLabelWidth">
                    <el-input
                            type="textarea"
                            autosize
                            placeholder="请输入内容"
                            v-model="form.smsContent"
                            :autosize="{ minRows: 3}">
                    </el-input>
                    <div class="tip">剩余可添加<span>{{count}}</span>字</div>
                    <el-popover
                            v-model="showPop"
                            ref="popover"
                            placement="bottom"
                            :disabled="disablePopover"
                            width="280"
                            @hide="hidePopover"
                            trigger="click">
                        <div class="message">短信类型：</div>
                        <el-autocomplete
                            class="inline-input"
                            v-model="typeName"
                            size="small"
                            :fetch-suggestions="querySearch"
                            placeholder="请输入短信类型">
                        </el-autocomplete>
                        <el-button type="primary" class="top_save1" @click="saveType" size="mini"><i class="fa fa-save"></i> 确 定</el-button>
                    </el-popover>
                    <el-button size="mini" type="primary" style="float: right;margin-top: 8px" @click="save" v-popover:popover>保存为自添加模板</el-button>
                </el-form-item>

                <el-form-item label="签名 : " :label-width="formLabelWidth">
                    <div v-model="smsSign" class="smsSign">--{{userData.userName}}</div>
                    <div class="tip">（签名也计入字数）</div>
                </el-form-item>

                <el-form-item label="发送方式 : " :label-width="formLabelWidth">
                    <el-radio class="radio" v-model="form.taskStatus" label="0">立即发送</el-radio>
                    <el-radio class="radio" v-model="form.taskStatus" label="1">定时发送</el-radio>
                    <el-date-picker
                            :picker-options="pickerOptions"
                            v-show="form.taskStatus == 1"
                            class="detepicker"
                            size="small"
                            v-model="form.sendTimingTime"
                            type="datetime"
                            placeholder="选择日期时间">
                    </el-date-picker>
                </el-form-item>
            </el-form>
        </div>
        <div class="message-right">
            <div style="width: 100%">
                <div class="templateType">
                    <span>模板类型：</span>
                    <el-select v-model="form.smsTempId"  size="small" style="width:140px" @change="handleTemplateType">
                        <el-option
                                v-for="item in templateType"
                                :key="item.value"
                                :label="item.value"
                                :value="item.key">
                        </el-option>
                    </el-select>
                </div>
                <div class="messageType">
                    <span>短信类型：</span>
                    <el-select v-model="form.smsType" size="small" style="width:140px" @change="handleMessageType">
                        <el-option
                                v-for="item in messageType"
                                :key="item.value"
                                :label="item.value"
                                :value="item.key">
                        </el-option>
                    </el-select>
                </div>
            </div>

            <el-table
                    :show-header = "false"
                    :data="templateList"
                    height="245"
                    stripe
                    border
                    @row-click="rowClick"
                    style="width: 100%">
                <el-table-column
                        prop="content">
                </el-table-column>
            </el-table>
        </div>

        <el-row class="action-btn">
            <el-col :span="12">
                <el-button type="primary" class="top_save" @click="sendMessage" size="small"><i class="fa fa-save"></i> 发 送</el-button>
            </el-col>
            <el-col :span="12">
                <el-button type="danger" class="top_close" @click="closeMsgDialog"  size="small"><i class="fa fa-sign-out"></i> 关 闭</el-button>
            </el-col>
        </el-row>
    </el-dialog>
</template>

<script>
    import Vue from 'vue'
    import {Dialog , Form , FormItem, Input, Button ,Message ,Radio,DatePicker ,Autocomplete,Popover} from 'element-ui'
    import {SHOW_MESSAGE} from '../store/mutation-types/template/index';
    import { mapGetters } from 'Vuex'
    import { validTel ,getDate} from '../utils/auth'

    Vue.use(Dialog);
    Vue.use(Form);
    Vue.use(FormItem);
    Vue.use(Input);
    Vue.use(Button);
    Vue.use(Radio);
    Vue.use(DatePicker);
    Vue.use(Autocomplete);
    Vue.use(Popover);

    export default {
        data () {
            return {
                showPop: false,
                disablePopover: true,
                typeOptions: [],
                typeName: '',
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() < Date.now() - 8.64e7;
                    }
                },
                templateType: [],
                messageType: [],
                templateList: [],
                formLabelWidth: '100px',
                form: {
                    receiveUserIds: [],   //接受人id
                    receiveTels: [],    //接受人电话
                    receiveNames: [],   //接受人名字

                    sendUserId: '',    //发送人id
                    deptCode: '',    //发送人部门code

                    smsTempId:'',   // 模板ID
                    smsContent:'',   //短信内容
                    smsSign: '',    //短信签名
                    smsType: '',    //短信id
                    taskStatus: '0',   //是否定时，0一般发送，1定时
                    sendTimingTime: ''   //定时时间
                },
                isAdmin: false,
                dictType: {
                    typeName: '',
                    typeId: '201',
                    des: '短信'
                },
                detail: {
                    templateType: 2,
                    templateSubtype: '',
                    content: '',
                },
            }
        },
        props: {
            'userData':{
                default: {}
            },
            'from':{
                default: 'index'
            }
        },
        methods: {
            rowClick(row, event, column) {
                this.form.smsContent = row.content;
            },
            closeMsgDialog() {
                this.$store.commit(SHOW_MESSAGE , {showMessage : false});
            },
            handleTemplateType(val) {
                this.form.smsTempId = val;
                var filter = {
                    'type':this.form.smsTempId,
                    'templateType': 2,
                    'templateSubtype': this.form.smsType,
                };
                this.$store.dispatch('getListByFilter', filter)
                    .then((response) => {
                        var result = response.data;
                        if(result && result.data ){
                            this.templateList = result.data
                        }
                    })
            },
            handleMessageType(val) {
                this.form.smsType = val;
                var filter = {
                    'type':this.form.smsTempId,
                    'templateType': 2,
                    'templateSubtype': this.form.smsType,
                };
                this.$store.dispatch('getListByFilter', filter)
                    .then((response) => {
                        var result = response.data;
                        if(result && result.data ){
                            this.templateList = result.data
                        }
                    })
            },
            save() {
                if(this.form.smsContent==''){
                    this.disablePopover = true;
                    Message.warning({
                        message: '请先输入短信内容'
                    });
                    return;
                }
                this.disablePopover = false;
            },
            saveType() {
                if(this.typeName == '') {
                    Message.warning({
                        message: '请先输入短信类型'
                    });
                    return;
                }
                this.dictType.typeName = this.typeName;
                this.$store.dispatch('addDictType', this.dictType)
                    .then((response) => {
                        let result = response.data;
                        if (result.code === 0) {
                            this.detail.templateSubtype = result.data;
                            this.detail.content = this.form.smsContent;
                            this.$store.dispatch('addTemplate', this.detail)
                                .then((response) => {
                                    let result = response.data;
                                    if (result.code === 0) {
                                        Message.success({
                                            message: '保存成功'
                                        });
                                        this.typeName='';
                                        this.showPop = false;
                                    }
                                });
                        }
                    });
            },
            empty() {
                this.form = {
                    receiveUserIds: [],   //接受人id
                    receiveTels: [],    //接受人电话
                    receiveNames: [],   //接受人名字

                    sendUserId: '',    //发送人id
                    deptCode: '',    //发送人部门code

                    smsTempId:'',   // 模板ID
                    smsContent:'',   //短信内容
                    smsSign: '',    //短信签名
                    smsType: '',    //短信id
                    taskStatus: '0',   //是否定时，0一般发送，1定时
                    sendTimingTime: ''   //定时时间
                }
            },
            sendMessage() {
                this.form.receiveUserIds = this.messageIds;
                this.form.receiveTels = this.messageTels;
                this.form.receiveNames = this.messageNames;
                this.form.sendUserId = this.userData.userId;
                this.form.deptCode = this.userData.deptCode;
                this.form.smsSign = this.smsSign;
                if(this.form.smsContent == ''){
                    Message.warning({
                        message: '请输入短信内容'
                    });
                    return;
                }else if(this.form.taskStatus == '1' && this.form.sendTimingTime == ''){
                    Message.warning({
                        message: '请选择定时发送的时间'
                    });
                    return;
                }
                if(this.form.sendTimingTime){
                    var sendTimingTime = getDate(this.form.sendTimingTime,true);   //转换日期时间格式
                    this.form.sendTimingTime = sendTimingTime;
                }
                this.$store.dispatch('sendMessage', this.form)
                    .then((response) => {
                        let result = response.data;
                        if (result.code === 0) {
                            Message.success({
                                message: '发送成功'
                            });
                            this.$store.commit(SHOW_MESSAGE , {showMessage : false});
                            this.empty();
                        }else {
                            Message.success({
                                message: '发送失败'+ result.message
                            });
                            this.$store.commit(SHOW_MESSAGE , {showMessage : false});
                            this.empty();
                        }
                    })
            },
            //搜索类型
            querySearch(queryString, cb) {
                var typeOptions = this.typeOptions;
                //typeOptions.shift();
                var results = queryString ? typeOptions.filter(this.createFilter(queryString)) : typeOptions;
                // 调用 callback 返回建议列表的数据
                cb(results);
            },
            createFilter(queryString) {
                return (typeOption) => {
                    return (typeOption.value.indexOf(queryString.toLowerCase()) === 0);
                };
            },
            hidePopover() {
                this.typeName='';
            }
        },
        computed:{
            ...mapGetters({
                'showMessageDialog': 'showMessage',
                'messageIds': 'getMessageIds',
                'messageNames': 'getMessageNames',
                'messageTels': 'getMessageTels'
            }),
            customerInfo: function () {
                switch (this.from){
                    case 'index':
                        var arr = new Array();
                        for(var i=0;i<this.messageIds.length;i++){
                            arr[i] = this.messageNames[i] + '|' + this.messageTels[i]
                        }
                        return arr.join(' ; ');
                        break;
                    case 'detail':
                        return this.messageNames + '|' + this.messageTels;
                        break;
                }

            },
            count: function () {
                let countNum = 275 - (4 + 2 + this.userData.userName.length) - this.form.smsContent.length;
                return countNum;
            },
            smsSign: function () {
                return '--' + this.userData.userName;
            }
        },
        created(){
            if (process.BROWSER_BUILD ) {
                const loggedUser = window.localStorage.getItem('token');
                if(loggedUser){
                    this.$store.dispatch('getTemplateList', {'templateType': 2})
                        .then((response) => {
                            var result = response.data;
                            if(result && result.data && result.data.templateDtoList &&  result.data.templateDtoList.length>0){
                                this.isAdmin = result.data.isAdmin;
                                if(this.isAdmin == true){
                                    this.templateType = [{
                                        key: '',
                                        value: '全部'
                                    },{
                                        key: '1',
                                        value: '自添加模板'
                                    }]
                                }else {
                                    this.templateType = [{
                                        key: '',
                                        value: '全部'
                                    },{
                                        key: '2',
                                        value: '常用模板'
                                    },{
                                        key: '1',
                                        value: '自添加模板'
                                    }]
                                }
                                this.templateList = result.data.templateDtoList;
                            }
                        });
                    //获取模板类型
                    this.$store.dispatch('getTemplateType', {'typeId': this.form.smsTempId})
                        .then((response) => {
                            let result = response.data;
                            if (result && result.code === 0) {
                                this.messageType = result.data;
                                this.messageType.unshift({key: '',value:'全部'})
                            }
                        });
                    //获取模板类型
                    this.$store.dispatch('getTemplateType', {'typeId': this.form.smsTempId})
                        .then((response) => {
                            let result = response.data;
                            if (result && result.code === 0) {
                                this.typeOptions = result.data;
                            }
                        });
                }
            }
        }
    }
</script>


<style scoped lang="scss">
    .top_close{
        float: left;
        margin-left: 20px;
        margin-top: 20px;
    }
    .top_close, .top_save{
        margin: 0 20px;
    }
    .top_save {
        float: right;
    }
    .top_save1 {
        margin-top: 25px;
        float: right;
        margin-right: 10px;
    }
    .message-left{
        width: 48%;
        float: left;
    }
    .message-right{
        width: 48%;
        float: right;
    }
    .action-btn , .action-btn1 {
        width: 100%;
        float: left;
        margin: 10px 0 30px 0;
    }
    .action-btn1 {
        margin: 10px 0 10px 0;
    }
    .smsSign ,.tip {
        display: inline-block;
        float: left;
    }
    .tip {
        font-size: 12px;
        color: #aaa;
        span {
            color: #ff0000;
        }
    }
    .templateType, .messageType {
        width: 50%;
        margin-bottom: 20px;
    }
    .templateType{
        float: left;
    }
    .messageType {
        float: right;
    }
    .detepicker {
        width: 150px !important;
        margin-left: 15px !important;
    }
    .inline-input {
        width: 120px;
        margin-top: 20px;
        margin-bottom: 15px;
    }
    .message{
        float:left;
        font-size: 14px;
        margin: 25px 0 15px 10px;
    }
</style>
